//
//  FileManager.swift
//  MyCloset
//
//  Created by 牟好好 on 2024/10/24.
//

import SwiftUI

class LocalFileManager {
    static let instance = LocalFileManager()
    let folderName = "Clothes"
    
    init() {
        //deleteFolder()
        createFolderIfNeeded()
    }
    
    func createFolderIfNeeded() {
        guard
            let path = FileManager
                .default
                .urls(for: .cachesDirectory, in: .userDomainMask)
                .first?
                .appendingPathComponent(folderName)
                .path else {
            return
        }
        
        if !FileManager.default.fileExists(atPath: path) {
            do {
                try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
                print("创建目录成功")
            } catch let error {
                print("创建目录失败: \(error.localizedDescription)")
            }
        }
    }
    
    // 用于清空缓存（暂时不需要）
    func deleteFolder() {
        guard
            let path = FileManager
                .default
                .urls(for: .cachesDirectory, in: .userDomainMask)
                .first?
                .appendingPathComponent(folderName)
                .path else {
            return
        }

        do {
            try FileManager.default.removeItem(atPath: path)
            print("删除文件夹成功")
        } catch let error {
            print("删除文件夹失败: \(error.localizedDescription)")
        }
    }
    
    // 删除临时目录，清除实况图片占用的内存
    func deleteTempFolder() {
        let tempDirectory = FileManager.default.temporaryDirectory
        
        do {
            let files = try FileManager.default.contentsOfDirectory(at: tempDirectory, includingPropertiesForKeys: nil)
            for file in files {
                try FileManager.default.removeItem(at: file)
            }
            print("删除文件夹成功")
        } catch let error {
            print("删除文件夹失败: \(error.localizedDescription)")
        }
    }
    
    // 保存图片到对应目录
    func saveImage(image: UIImage, id: UUID) -> (String, String?) {
        guard let data = image.jpegData(compressionQuality: 0.5),
              let path = getPathForImage(id: id) else {
                  return ("获取数据失败！", nil)
        }
        
        // 保存文件到该目录
        do {
            try data.write(to: path)
            return ("保存成功!", path.path)
        } catch let error {
            return ("保存失败:\(error.localizedDescription)", nil)
        }
    }
    
    // 从文件管理器中获取图片
    func getImage(id: UUID) -> UIImage? {
        guard let path = getPathForImage(id: id)?.path,
              FileManager.default.fileExists(atPath: path) else {
            print("获取资源路径失败!")
            return nil
        }
        
        return UIImage(contentsOfFile: path)
    }
    
    // 删除文件管理器中的图片
    func deleteImage(id: UUID) -> String {
        guard let path = getPathForImage(id: id),
              FileManager.default.fileExists(atPath: path.path) else {
            return "获取资源路径失败!"
        }
        
        do {
            try FileManager.default.removeItem(at: path)
            return "删除成功"
        } catch let error {
            return "删除失败:\(error.localizedDescription)"
        }
    }
    
    func getPathForImage(id: UUID) -> URL? {
        guard
            let path = FileManager
                .default
                .urls(for: .cachesDirectory, in: .userDomainMask)
                .first?
                .appendingPathComponent(folderName)
                .appendingPathComponent("\(id).jpg") else {
            print("获取路径失败!")
            return nil
        }
        return path
    }
}
